package util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWTVerifier;
 
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class JWTUtil {
	private static final String SIGN = "LYZ"; //密钥
	 
    //1.通过JWT生成token字符串。
    public static String createToken(Map <String, Object> params) {
    	//Map的Object有限制：Map、List、Boolean、Integer、Long、Double、String 或者 Date 类型的数据
        Map<String, Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");
 
        //定义颁发时间
        Date iss = new Date();
        //过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 30);
        Date expire = nowTime.getTime();
 
        String token = JWT.create()
                //指定头信息
                .withHeader(head)
                //载荷种的过期时间
                .withExpiresAt(expire)
                //颁发时间
                .withIssuedAt(iss)
                //颁发人
                .withIssuer("LYZ")
                //自定义的载荷内容
                .withClaim("userInfo", params)
                //签名 加密
                .sign(Algorithm.HMAC256(SIGN));
 
        return token;
    }
 
    //2. 判断token是否合法
    public static boolean verifyToken(String token) {
        //通过秘钥解密判断
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        try {
            DecodedJWT verify = build.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 通过token获取用户的id
     * @param token
     * @return
     */
    public static String getToken(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
        DecodedJWT jwt = verifier.verify(token);
        String jwtSubject = jwt.getSubject();
        return String.valueOf(jwtSubject);
    }

}
